<?php

namespace common\models\datas;

use common\components\bases\BaseModel;
use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use frontend\models\datas\Mechanic;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%complaint}}".
 *
 * @property integer $id
 * @property integer $customer_id
 * @property integer $mechanic_id
 * @property integer $service_level
 * @property integer $teaching_level
 * @property integer $environmental_level
 * @property integer $status
 * @property string $complaint_content
 * @property integer $admin_id
 * @property string $admin_name
 * @property string $remarks
 * @property integer $created_at
 * @property integer $updated_at
 */
class Apply extends BaseModel
{
    public $new_remark;
    public $dues_proportion;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%apply}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['telephone', 'student_name', 'borth_year', 'borth_month','remarks','new_remark','v_code'], 'string'],
            [['telephone'], 'match', 'pattern' => '/^1[3|4|5|7|8]\d{9}$/', 'message' => '请正确输入手机号码'],
            [['primary_classification_id', 'secondary_classification_id','created_at','updated_at','status','card_type','site_id','mechanic_id','dues_proportion','card_attr_id','operator_id','mode'], 'integer'],
            [['telephone'],'required'],
            [['student_name'],'required','on'=>'apply'],
            [['new_remark'],'required','on' => ['handle']],
            [['telephone'],'check_unique','on'=>'apply'],
            [['telephone'],'unique','on'=>'apply','targetAttribute' => ['telephone', 'site_id']],
            [['v_code'],'match','pattern'=>'/^\w{6}$/','message' => '请输入6位格式的激活码','on'=>'apply'],
            [['v_code'],'check_codeeffective','on'=>'apply'],
            [['site_id'],'required','when' => function($model) {
                return empty($model->v_code);//当激活码为空的时候需要验证siteid不能为空
            },'on'=>'apply']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '自增id'),
            'telephone' => Yii::t('common', '联系方式'),
            'student_name' => Yii::t('common', '学员姓名'),
            'borth_year' => Yii::t('common', '出生年份'),
            'borth_month' => Yii::t('common', '出生月份'),
            'primary_classification_id' => Yii::t('common', '意向科目大类'),
            'secondary_classification_id' => Yii::t('common', '意向科目小类'),
            'status' => Yii::t('common', '状态'),
            'created_at' => Yii::t('common', '申请时间'),
            'updated_at' => Yii::t('common', '处理时间'),
            'remarks' => Yii::t('common', '备注历史'),
            'site_id' => Yii::t('common','分店id'),
            'mechanic_id' => Yii::t('common','机构id'),
            'new_remark'  => Yii::t('common','备注'),
            'dues_proportion'=>Yii::t('common','优惠会费比例'),
            'card_attr_id' => Yii::t('common','激活码id'),
            'v_code' => Yii::t('common','激活码'),
            'operator_id'=>Yii::t('common','操作人id'),
            'operator'=>Yii::t('common','操作人'),
            'card_type'=>Yii::t('common','卡类型'),
            'mode'=>Yii::t('common','请求所属类型（1共同体 2综合体 3管弦乐）')
        ];
    }

    public function fields(){

        $fields = parent::fields();
        $fields['created_at'] = function(){
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['updated_at'] = function(){
            if($this->updated_at == 0){
                return Yii::t('common','未处理');
            }else{
                return \Yii::$app->formatter->asDatetime($this->updated_at);
            }
        };
        $fields['status'] = function(){
             switch($this->status){
                 case 0:
                    return Yii::t('common','申请中');
                 case 1:
                     return Yii::t('common','审核中');
                 case 2:
                     return Yii::t('common','申请通过');
                 case 3:
                     return Yii::t('common','申请失败');
             }
        };
        return $fields;

    }

    public function extraFields(){
        return [
            'datebirth' => function(){
                return $this->borth_year.'年'.$this->borth_month.'月';
            },
            'cate_name'=>function(){
                return isset($this->cate)?$this->cate->name:isset($this->parentCate)?$this->parentCate->name:'';
            },
            'mechanic_name'=>function(){
                return isset($this->mechanic)?$this->mechanic->name:'豆苗朵';
            },
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'handle' => function ($data) {
                            if (in_array($data['status'],[2,3])) {
                                return '<button class="yx-btn-disabled" type="button">完成</button>';
                            } else {
                                return '';
                            }
                        },
                        'view'=>function(){
                            return '';
                        }
                    ]
                )->create();
            },
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ]);
    }

    /*针对已存在用户的唯一性判断*/
    public function check_unique($attribute){
        $current_mode = $this->mode;
        switch ($current_mode){
            case 1:
                $mode_name = "共同体";
                break;
            case 2:
                $mode_name = "综合体";
                break;
            case 3:
                $mode_name = "管弦乐";
                break;
            default:
                $mode_name = '';
                break;
        }
        $apply = Apply::findOne(['telephone'=>$this->$attribute,'mode'=>$current_mode]);
        if(!empty($apply)){
            $this->addError($attribute, Yii::t('frontend','对不起，已经提交过对应'.$mode_name.'的申请'));
        }else{//申请表没有问题，开始检验customer表是否有问题
            $customer = Customer::findOne(['mobile'=>$this->$attribute]);
            if(!empty($customer)){
                if(!empty($customer->gttopenid)){
                    $this->addError($attribute, Yii::t('frontend','该手机号已是会员'));
                }
            }
        }
    }

    public function check_codeeffective($attribute){
        $current_mode = $this->mode;
        switch ($current_mode){
            case 1:
                $mode_name = "共同体";
                break;
            case 2:
                $mode_name = "综合体";
                break;
            case 3:
                $mode_name = "管弦乐";
                break;
            default:
                $mode_name = '';
                break;
        }
        $card_attr = CardAttr::find()->where(['v_code' => $this->$attribute,'sendtype'=>0,'customer_id'=>NULL])->andWhere(['in','status',[0,2]])->andWhere(['>', 'salesman_id', 0])->one();//仅针对实体卡
        /*激活码需要属于对应的类型*/
        if(empty($card_attr)){
            $this->addError($attribute, Yii::t('frontend', '对不起，该激活码无效'));
        }else{
            $site_id = $card_attr->site_id;
            if(!empty($site_id)){
                $site = Site::findOne($site_id);
                if(empty($site->mode)){
                    $this->addError($attribute, Yii::t('frontend', '对不起，当前激活码所属的类型不存在'));
                }else{
                    if($site->mode != $current_mode){
                        $this->addError($attribute, Yii::t('frontend', '激活码不属于当前'.$mode_name.'的类型'));
                    }
                }
            }
        }
    }

    public function getCate(){
        return $this->hasOne(Cate::className(),['id'=>'secondary_classification_id']);
    }
    public function getParentCate(){
        return $this->hasOne(Cate::className(),['id'=>'primary_classification_id']);
    }

    public function getMechanic(){
        return $this->hasOne(Mechanic::className(),['id'=>'mechanic_id']);
    }

    public function getSite(){
        return $this->hasOne(Site::className(),['id'=>'site_id']);
    }

}
